#include "main.h"
#include "gpio.h"
#include "spi.h"
#include "ws2812.h"

RGB_Color_Type_t R_color={0xFF,0x00,0x00};
RGB_Color_Type_t B_color={0x00,0xFF,0x00};
RGB_Color_Type_t G_color={0x00,0x00,0xFF};
RGB_Color_Type_t Y_color={0xFF,0xFF,0x00};

BreatheLight_Handle_Type_t breathelight_tcb;
Light_Hande_Type_t         light_tcb;          //
Blink_Handle_Type_t        blink_tcb;
RGB_Color_Type_t color_close={0,0,0};
void LED_Load(uint8_t* buf,uint16_t len)
{
	HAL_SPI_Transmit_DMA(&hspi2,buf,len);
}
void Set_Light_Color(RGB_Color_Type_t color)
{
	SET_Color(color.G,color.R,color.B);
	LED_Load(led_buf,LED_BUF_LEN);
}
/// @brief 呼吸灯初始化
/// @param handle 
void Breathe_Init(BreatheLight_Handle_Type_t *handle)
{
	handle->max=70;
	handle->min=5;
	handle->brightness=0;
	handle->step=0.5;
	handle->dir=1;
}
/// @brief 闪烁灯初始化
/// @param handle 
void Blink_Init(Blink_Handle_Type_t *handle)
{
	handle->Open_Pulse=250;
	handle->period=500;
	handle->step_time=10;
	handle->time=0;
}
/// @brief 闪烁灯运行
/// @param handle 
void Blink_Color(Blink_Handle_Type_t *handle)
{
	handle->time+=handle->step_time;
	if(handle->time<handle->Open_Pulse)
	{
		Set_Light_Color(light_tcb.color);
	}
	else
	{
		Set_Light_Color(color_close);
	}
	if(handle->time>handle->period)
	{
		handle->time=0;
	}
}
/// @brief 呼吸灯运行
/// @param handle 
void Breathe_Color(BreatheLight_Handle_Type_t *handle)
{
	if(handle->dir)
	{
		if(handle->brightness<handle->max)
		{
			handle->brightness+=handle->step;
		}
		else
		{
			handle->dir=0;
		}
	}
	else
	{
		if(handle->brightness>handle->min)
		{
			handle->brightness-=handle->step;
		}
		else
		{
			handle->dir=1;
		}
	}
	handle->color.R=light_tcb.color.R*(handle->brightness/100.0);
	handle->color.G=light_tcb.color.G*(handle->brightness/100.0);
	handle->color.B=light_tcb.color.B*(handle->brightness/100.0);
	Set_Light_Color(handle->color);
}
/// @brief WS2812 任务函数
/// @param paremeter 线程入口参数
void WS2812_thread_entry(void *paremeter)
{
	RGB_Color_Type_t color;
	color.R=0x00;
	color.G=0x77;
	color.B=0x77;
	//LED_GPIO_Init();
	Breathe_Init(&breathelight_tcb);
	Blink_Init(&blink_tcb);
	Set_Light(Breathe,Y_color);
	while(1)
	{
		if(light_tcb.model==Breathe)
		{
			Breathe_Color(&breathelight_tcb);
		}
		else if(light_tcb.model==blink)
		{
			Blink_Color(&blink_tcb);
		}
		else if(light_tcb.model==Light_NO)
		{
			Set_Light_Color(light_tcb.color);
		}
		else if(light_tcb.model==Light_close)
		{
			Set_Light_Color(color_close);
		}
		LED_Load(led_buf,LED_BUF_LEN);
		rt_thread_mdelay(10);
	}
}
void Set_Blink_Light(RGB_Color_Type_t color)
{
	light_tcb.model=blink;
	light_tcb.color=color;
	blink_tcb.color=color;
}

void Set_breathe_Light(RGB_Color_Type_t color)
{
	light_tcb.model=Breathe;
	light_tcb.color=color;
	breathelight_tcb.color=color;
}

void Set_Light(uint8_t model,RGB_Color_Type_t color)
{
	light_tcb.model=model;
	light_tcb.color=color;
}

